package.path = package.path .. ";./../../llib/?.lua";
x = require("lglx");
print(x);
sdl2 = true;
print(require("readud"));
print(require('dcall'));
drw_test = require("drw")

print(drw_test);
    theta = 0.0;
if(window)then 
    print(require("glTest"));
    print(x);
    print(createGLWindow);
    print(destroyWindow);
    print(peekMessage);

    print(glBegin);

    glBegin(2);

    glEnd();


    local w = createGLWindow("TEST",256,256);
    while(true)do
        local x = peekMessage(w,function()
              if(red==nil)then
                red = 0.0;
              else
                if(red<1.0)then
                  red = red + 0.01;
                else
                  red = 0.0;
                end
              end
              glClearColor(red, 0.0, 0.0, 0.0);
              glClear(GL_COLOR_BUFFER_BIT);

              glPushMatrix();
              glRotatef(theta, 0.0, 0.0, 1.0);
              glBegin(GL_TRIANGLES);
              --glColor3f( 1.0, 0.0, 0.0 ); glVertex2f( 0.0, 1.0 );
              glColor3f( 1.0, 0.0, 0.0 ); glVertex2f( 0.0 ,1.0);  --去掉一个参数测试
              glColor3f( 0.0, 1.0, 0.0 ); glVertex2f( 0.87, -0.5 );
              gl.Color3f( 0.0, 0.0, 1.0 ); gl.Vertex2f( -0.87, -0.5 );
              glEnd();
              theta = theta + 1.0;
        end);
        if(x>0)then
            break;
        end
    end
    destroyWindow(w);
end

function glTest()
      if(red==nil)then
        red = 0.0;
      else
        if(red<1.0)then
          red = red + 0.01;
        else
          red = 0.0;
        end
      end

      glPushMatrix();
      glRotatef(theta, 0.0, 0.0, 1.0);
      glBegin(GL_TRIANGLES);
      --glColor3f( 1.0, 0.0, 0.0 ); glVertex2f( 0.0, 1.0 );
      glColor3f( 1.0, 0.0, 0.0 ); glVertex2f( 0.0 ,1.0);  --去掉一个参数测试
      glColor3f( 0.0, 1.0, 0.0 ); glVertex2f( 0.87, -0.5 );
      glColor3f( 0.0, 0.0, 1.0 ); glVertex2f( -0.87, -0.5 );

      glEnd();
      theta = theta + 1.0;
end


if(sdl2)then
    local oldtick = 0;
    print("toArray ",require("toArray"));
    print(require("lSDL"));
    print(require("2dTexture"));
    print("SDL_image",require("lSDL_image"));

    
    --SDL_GL_CONTEXT_MAJOR_VERSION = 17;
    --SDL_GL_CONTEXT_MINOR_VERSION = 18;
    --SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    --SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    
    SDL_Init(-1);
    
    --如果注释这行，会使用着色器渲染。会出现颜色问题
    --SDL_SetHint("SDL_RENDER_OPENGL_SHADERS","0");
    
    
    opengl = 2;
    shown = 4;
    posx = 0x1FFF0000;
    posy = 0x1FFF0000;
    --[[
    --posx = SDL_WINDOWPOS_UNDEFINED;--0x1FFF0000;
    --posy = SDL_WINDOWPOS_UNDEFINED;--0x1FFF0000;
    
#define SDL_WINDOWPOS_UNDEFINED 0x1FFF0000
not enum
    ]]
    w = SDL_CreateWindow("test",posx,posy,640,480,opengl+shown);
    
    r = SDL_CreateRenderer(w,2,SDL_RENDERER_TARGETTEXTURE+SDL_RENDERER_ACCELERATED+SDL_RENDERER_PRESENTVSYNC);
    g = SDL_GL_CreateContext(w);
    --SDL_GL_SetSwapInterval(0);
    dst = SDL_calloc(4*4,1);
    
    function SDL_LoadBMP(f)
        return SDL_LoadBMP_RW(SDL_RWFromFile(f, "rb"), 1);
    end
    
    x = SDL_malloc(1024);
    mem = SDL_calloc(1,1024);
    null = dpointer(0);
    
    IMG_Init(-1);

    s = SDL_LoadBMP("test.bmp");
    texture = SDL_CreateTextureFromSurface(r,s);
    SDL_DestroyTexture(texture);
    SDL_FreeSurface(s);
    texture = IMG_LoadTexture(r,"test.png");

    local buf = "abcdefgh";
    local buf1 = "abcdefgh";
    SDL_QueryTexture(texture,buf,buf1,buf1,buf1);
    local pixformat = SDL_PIXELFORMAT_RGBA8888;
    --local pixformat = buf:byte(1)+(buf:byte(2)<<8)+(buf:byte(3)<<0x10)+(buf:byte(4)<<0x18);
    --print(pixformat);
    --print(dtostring(SDL_GetPixelFormatName(pixformat)));
    
    gltexture = SDL_CreateTexture(r,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_TARGET,640,480);
    
    local dglUseProgram = SDL_GL_GetProcAddress("glUseProgram");
    print("gl    ",dglUseProgram);
    function glUseProgram(v)
        --dcall(dglUseProgram,v);
        return stdcall(dglUseProgram,v);
    end
    dcall(printf,"%d %d\n",11,22);
    
    --print(glUseProgram(0));
    
    local ttexture = SDL_CreateTexture(r,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_TARGET,640,480);
    SDL_SetRenderTarget(r,ttexture);
    SDL_SetRenderDrawColor(r,0xFF,0xFF,0xFF,0xff);
    SDL_RenderClear(r);
    
    SDL_RenderCopy(r,texture,null,null);
    
    SDL_RenderPresent(r);
    SDL_SetRenderTarget(r,null);
    SDL_DestroyTexture(texture);
    texture = ttexture;
    
    --SDL_SetRenderDrawBlendMode(r,SDL_BLENDMODE_BLEND);
    
    --SDL_SetTextureBlendMode(texture,SDL_BLENDMODE_BLEND);
    --SDL_SetTextureAlphaMod(texture,0xff);
    --SDL_SetTextureColorMod(texture,0xfe,0xfe,0xfe);
    
    --SDL_SetRenderDrawBlendMode(r,SDL_BLENDMODE_NONE);
    
    --SDL_SetTextureBlendMode(gltexture,SDL_BLENDMODE_BLEND);
    --SDL_SetTextureAlphaMod(gltexture,0xff);
    --SDL_SetTextureColorMod(gltexture,0xfe,0xfe,0xfe);
    --SDL_SetTextureColorMod(gltexture,0x1,0x1,0x1);
    
    --SDL_SetTextureBlendMode(texture,SDL_BLENDMODE_BLEND);
    --SDL_SetTextureAlphaMod(texture,0xff);
    --SDL_SetTextureColorMod(texture,0xfe,0xfe,0xfe);
    
    --null = SDL_malloc(-1);
    
    print("null ptr",null);
    test_sdl_texture = 1;
    
    function toArray(mm,typ)
        if(typ==nil)then typ = 1; end;
        local metatable = {
            __index = function(m,k)
                if(type(k)=="number")then
                    return dr(m,k*typ,typ);
                else
                    return nil;
                    --return rawget(m,k);
                end
            end,
            __newindex = function(m,k,v)
                return dw(m,k*typ,typ,v);
            end
        };
        udsetmetatable(mm,metatable);
        return mm;
    end
    
    mem = toArray(mem);
    x = toArray(x,4);
    
    
    if(drw_test)then
        SDL_memcpy(mem,"123456",7);
        local str = drstring(mem,0,6);
        print(str);
        local p = touserdata(mem);
        oldtouserdata = touserdata;
        function touserdata(m)
            local light = {
                __gc = function(m)
                    print("gc  ");
                end,
                read = function(m,off,siz)
                    if(siz==nil)then siz = 4;end;
                    if(off==nil)then off = 0;end;
                    return dr(m,off,siz);
                end,
                write = function(m,data,off,siz)
                    if(off==nil)then off = 0;end;
                    if(type(data)=="string")then
                        if(siz==nil)then siz = #data;end
                        dwstring(m,off,siz,data);
                    elseif(type(data)=="number")then
                        if(siz==nil)then siz = 4;end;
                        dw(m,off,siz,data);
                    else
                        SDL_memcpy(dpointer(m,off),data,siz);
                    end
                end,
                __index = function(m,k)
                    l = getmetatable(m);
                    return rawget(l,k);
                end
            };
            if(islightuserdata(m))then
                --lightuserdata 不带 __gc 回收 
                m = oldtouserdata(m);
                --m = {data = m};
                udsetmetatable(m,light);
                --setmetatable(m,light);
                print(getmetatable(m));
                print(m:read());
                print(m);
            end
            return m;
        end
        p = touserdata(mem);
    end
    frame = 0;
    
    print("user data?",isuserdata(x));
    --x = touserdata(x);
    print("user data?",isuserdata(x));
    getmetatable(x).__gc = function(d)
        SDL_free(d);
        print("SDL free",d);
    end
    
    while(true)do
        ctick = SDL_GetTicks();
        if((ctick-oldtick)>1000)then
            oldtick = ctick;
            local s = string.format("fps:%d",frame);
            SDL_SetWindowTitle(w,s);
            frame = 0;
        end
        frame = frame + 1;
        local e = SDL_PollEvent(x);
        --SDL_RenderClear(r);
        --local typ = readud(x,0,4);
        
        
        local typ;
        --local typ = dr(x,0,4);  
        if(drw_test)then
            typ = x[0];
            --typ = x:read();
        else
            typ = dr(x,0,4);  
        end
        --print(x[1]);
        
        --print(typ);
        if(typ==256)then
            break;
        end
        --glTest();
        if(true)then

            --SDL_RenderCopy(r,texture,null,null);
            --glTest();
            --SDL_RenderPresent(r);
        --else
          if(ww==nil)then ww = 400;
          else
            ww = ww + 1;
          end
          
          --glClearColor(0, 0.0, 0.0, 0.0);
          --glClear(GL_COLOR_BUFFER_BIT);
          
          -- glViewport(0,0,640,480);
          -- glMatrixMode(GL_PROJECTION);  
          -- glLoadIdentity();
          SDL_SetRenderDrawColor(r,0xff,0xff,0xFF,0xff);
          SDL_RenderClear(r);
          
          SDL_GetRenderDrawBlendMode(r,buf);
          --local bmode = buf:byte(1)+(buf:byte(2)<<8)+(buf:byte(3)<<0x10)+(buf:byte(4)<<0x18);
          --print(bmode);
          
          SDL_RenderSetViewport(r,null);
          
          
          useSDLTexture = true;
          renderImage = true;
          rendergl = true;
          
          if(renderImage)then
            SDL_RenderCopy(r,texture,null,null);
            --glClearColor(0, 0.0, 0.0, 0.0);  --透明色，如果不设置则不会透明
            --glClear(GL_COLOR_BUFFER_BIT);    --清空所有颜色，如果不设置，则不会清空
          end
          
          
          
          --if(xxx==nil)then
          if(true)then
          xxx = 1;
          if(useSDLTexture and SDL_SetRenderTarget(r,gltexture)~=0)then
            print("error");
            print(dtostring(SDL_GetError()));
          end
          
          if(program==nil)then
          program = true;
          glUseProgram(0);
          end
          
          SDL_SetTextureBlendMode(gltexture,SDL_BLENDMODE_BLEND);
          -- SDL_GetRenderDrawBlendMode(r,buf);
          -- local bmode = buf:byte(1)+(buf:byte(2)<<8)+(buf:byte(3)<<0x10)+(buf:byte(4)<<0x18);
          -- print(bmode);
          
          if(renderImage==nil or useSDLTexture)then
            if(renderImage)then  --如果有背景，则渲染不出来
                glClearColor(0, 0.0, 0.0, 0.0);  --透明色，如果不设置则不会透明
            else
                --如果glClearColor，则会不会渲染
            end
            
            glClear(GL_COLOR_BUFFER_BIT);    --清空所有颜色，如果不设置，则不会清空
          end
          
          if(rendergl)then
          --glBlendFunc(GL_ZERO, GL_ONE);
          glViewport(0,0,640,480);
          glMatrixMode(GL_PROJECTION);  
          glLoadIdentity();
          glTest();
          
          for k=0,30 do
              for kk=0,30 do
                  glViewport(0+k*30,0+kk*30,30,30);
                  glMatrixMode(GL_PROJECTION);  
                  glLoadIdentity();
                  glTest();
              end
              
          end
          
          --如果不设置，直接渲染到屏幕会变色
          --渲染到纹理，则不会变色
          glColor3f(1,1,1);
          
          end
          --SDL_RenderPresent(r);
          --SDL_GL_SwapWindow(w);
          if(SDL_SetRenderTarget(r,null)~=0)then
            print("error");
            print(dtostring(SDL_GetError()));
          else
            if(useSDLTexture)then
                --SDL_RenderCopy(r,gltexture,null,null);
                
                local x = 0;
                local y = 0;
                local w = bit.rshift(640,1);
                local h = bit.rshift(480,1);
                dw(dst,0,4,x);
                dw(dst,4,4,y);
                dw(dst,8,4,w);
                dw(dst,12,4,h);
                
                SDL_RenderCopy(r,gltexture,null,dst);
                
                if(renderImage)then 
                    x = 320;
                    y = 240;
                    w = 640;
                    h = 480;
                    dw(dst,0,4,x);
                    dw(dst,4,4,y);
                    dw(dst,8,4,w);
                    dw(dst,12,4,h);
                    SDL_RenderCopy(r,texture,null,dst);
                end
            end
          end
          
          end
          
          --SDL_RenderCopy(r,texture,null,null);
          --glTest2dTexure();
          SDL_RenderPresent(r);
          SDL_Delay(1000/60/2);
          --SDL_GL_SwapWindow(w);
        end
        --SDL_RenderPresent(r);
    end
    --SDL_free(x);
    local buf = "abcdefgh";
    glGetIntegerv(GL_MAX_TEXTURE_SIZE,buf);
    --local size = buf:byte(1)+(buf:byte(2)<<8)+(buf:byte(3)<<0x10)+(buf:byte(4)<<0x18)
    --print("max texture size:",string.format("%X",size),size);
    GL_MAX_TEXTURE_UNITS=0x84E2;
    GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872;
    glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,buf);
    --local size = buf:byte(1)+(buf:byte(2)<<8)+(buf:byte(3)<<0x10)+(buf:byte(4)<<0x18)
    --print("max texture units:",string.format("%X",size),size);
    
    SDL_DestroyRenderer(r);
    SDL_DestroyWindow(w);
    IMG_Quit();
    SDL_Quit();
end



